import axios from 'axios'
import store from '@/store'
import {Message, MessageBox} from 'element-ui'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 50000 // request timeout
})

// request interceptor sessionStorage.getItem('SET_TOKEN')
service.interceptors.request.use( config => {
    config.headers.common = {
    'Authorization': 'Bearer ' + getToken()
  }
  return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    if (res.code === 200) {
      return res
    } else {
      if (res.code === 401) {
        MessageBox.alert('您的授权已过期，是否重新登录？', '授权过期', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          location.reload()
        }).catch(() => {})
        /*Message({
          message: '您的登录已过期，请重新登录!',
          type: 'error'
        })*/
        return Promise.reject(res)
      }else {
        return Promise.reject(res)
      }
      // return Promise.reject(res)
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 2 * 1000
    })
    return Promise.reject(error)
  }
)

export default service.request
